//
//  LRRefreshControl.swift
//  WeiboX
//
//  Created by admin on 08/12/2016.
//  Copyright © 2016 iOS_Objective-C. All rights reserved.
//

import UIKit

// 下拉刷新的控件高度
private let lRRefreshControlHeight: CGFloat = 50
private enum LRRefreshControlType {
	// 下拉刷新
	case normal
	// 松手刷新
	case pulling
	// 正在刷新
	case refreshing
}

class LRRefreshControl: UIControl {
	
	private var refreshType: LRRefreshControlType = .normal{
		didSet {
			
			switch refreshType {
			case .normal:
				print("下拉刷新")
				// 显示箭头 停止菊花 箭头重置 文字: 下拉刷新
				arrow.isHidden = false
				indicator.stopAnimating()
				UIView.animate(withDuration: 0.25, animations: { 
					self.arrow.transform = CGAffineTransform.identity
				})
				info.text = "下拉刷新"
				
				// 判断上一次刷新状态是否是正在刷新
				if oldValue == .refreshing {
					UIView.animate(withDuration: 0.25, animations: { 
						self.currentScrollV?.contentInset.top -= lRRefreshControlHeight
					})
				}
				
			case .pulling:
				print("松手就刷新")
				// 箭头反向 文字: 松手就刷新
				UIView.animate(withDuration: 0.25, animations: { 
					self.arrow.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
				})
				info.text = "松手就刷新"
				
			case .refreshing:
				print("正在刷新")
				// 隐藏箭头 旋转菊花 文字: 正在刷新
				arrow.isHidden = true
				indicator.startAnimating()
				info.text = "正在刷新"
				
				// 设置控件的停留位置
				UIView.animate(withDuration: 0.25, animations: { 
					self.currentScrollV?.contentInset.top += lRRefreshControlHeight
				})
				
			sendActions(for: .valueChanged)
			}
		}
	}
	
	// 记录当前可以滚动的视图
	private var currentScrollV: UIScrollView?
	// 箭头
	private lazy var arrow: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
	// 菊花
	private lazy var indicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
	// info
	private lazy var info: UILabel = {
		let label = UILabel()
		label.text = "下拉刷新"
		label.font = UIFont.systemFont(ofSize: 12)
		label.textColor = .gray
		return label
	}()
	
	override init(frame: CGRect) {
		super.init(frame: frame)
//
//		let screenWidth = UIScreen.main.bounds.width
//		
//		self.frame.size = CGSize(width: screenWidth, height: lRRefreshControlHeight)
//		self.frame.origin.y = -lRRefreshControlHeight
		
		setupUI()
	}
	
	required init?(coder aDecoder: NSCoder) {
		fatalError("init(coder:) has not been implemented")
	}
	
	private func setupUI() {
		backgroundColor = .yellow
		
		addSubview(arrow)
		addSubview(indicator)
		addSubview(info)
		
		arrow.translatesAutoresizingMaskIntoConstraints = false
		indicator.translatesAutoresizingMaskIntoConstraints = false
		info.translatesAutoresizingMaskIntoConstraints = false
		
		addConstraint(NSLayoutConstraint(item: arrow, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -35))
		addConstraint(NSLayoutConstraint(item: arrow, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
		addConstraint(NSLayoutConstraint(item: indicator, attribute: .centerX, relatedBy: .equal, toItem: arrow, attribute: .centerX, multiplier: 1, constant: 0))
		addConstraint(NSLayoutConstraint(item: indicator, attribute: .centerY, relatedBy: .equal, toItem: arrow, attribute: .centerY, multiplier: 1, constant: 0))
		addConstraint(NSLayoutConstraint(item: info, attribute: .leading, relatedBy: .equal, toItem: arrow, attribute: .trailing, multiplier: 1, constant: 0))
		addConstraint(NSLayoutConstraint(item: info, attribute: .centerY, relatedBy: .equal, toItem: arrow, attribute: .centerY, multiplier: 1, constant: 0))
	}
	
	// 添加到父视图时会调用这个方法
	override func willMove(toSuperview newSuperview: UIView?) {
		// 判断父视图是否是可以滚动的控件
		guard let scrollV = newSuperview as? UIScrollView else {
			return
		}
		
		self.frame.size = CGSize(width: scrollV.frame.size.width, height: lRRefreshControlHeight)
		self.frame.origin.y = -lRRefreshControlHeight
		
		// kvo 监听 scrollV 的 contentOffSet 的变化
		scrollV.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
		currentScrollV = scrollV
	}
	
	
	// 监听的方法
	override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
		// 取得垂直方向的偏移量
		let contentOffsetY = currentScrollV!.contentOffset.y
//		print(contentOffsetY)
		// 临界点 -144
		let maxY = CGFloat(-114)
//		print(currentScrollV?.contentInset.top)
		if currentScrollV!.isDragging {
			if contentOffsetY < maxY && refreshType == .normal{
				refreshType = .pulling
			} else if contentOffsetY >= maxY && refreshType == .pulling {
				refreshType = .normal
			}
		} else {
			//buzai tuozhuai
			if refreshType == .pulling {
				refreshType = .refreshing
			}
		}
	}
	
	// 结束刷新
	func endRefreshing() {
		refreshType = .normal
	}
	
	deinit {
		currentScrollV?.removeObserver(self, forKeyPath: "contentOffset")
	}
}
